package db
import (
	"fmt"
	_"github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
    "github.com/aWildProgrammer/fconf"
    "sync"
)

// 单例模式
var instance *sqlx.DB
var once sync.Once
var err string

type DbInfo struct {
    Engine string
    User   string
    Pass   string
    Ip     string
    Port   string
    Table  string
}

type Person struct {
	Username string
	Age int
}

func _init () (database *sqlx.DB, errorMsg string){
 	fmt.Println("链接数据库")
    c, error := fconf.NewFileConf("./config/config.ini")
    if error != nil {
        fmt.Println("读取配置文件错误 :", error)
        return 
    }
    db1 := DbInfo{
        "mysql",
        c.String("mysql.user"),
        c.String("mysql.password"),
        c.String("mysql.host"),
        c.String("mysql.port"),
        c.String("mysql.database"),
    }
    fmt.Println("数据连接信息", db1)
    database, err := sqlx.Open(db1.Engine, fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", db1.User, db1.Pass, db1.Ip, db1.Port, db1.Table))
    if err != nil {
        errorMsg = "mysql open failed, error:" + err.Error()
        fmt.Println(errorMsg)
    }
    return database,errorMsg
}

func ConnectMysql() *sqlx.DB {
    once.Do(func() {
        instance,err = _init()
    })
    return instance
}